package gui.common;

import java.text.DecimalFormat;
import java.util.Collection;

import gui.product.ProductData;
import coreModel.HIT;
import coreModel.Item;
import coreModel.ItemManager;
import coreModel.Product;
import coreModel.ProductContainer;


import coreModel.Unit;
import java.lang.Object;

public class DataConverter
{
	/**
	 * Convert a model product to a view product
	 * @param p the model product you want to convert
	 * @param parent the parent of product you want to convert. Pass in NULL if 
	 * you are in the root and there is no parent
	 * @return the converted view product
	 */
	public static ProductData ConvertProduct(Product p, ProductContainer parent)
	{
		
		ItemManager iMgr = HIT.getInstance().getItemManager();
		
		Collection<Item> pItems;
		if (parent == null)
			pItems = iMgr.getAllItemsOfProduct(p);
		else
			pItems = iMgr.getItemsByContainerAndProduct(parent, p);
		
		int intCount;
		if (pItems == null)
			intCount = 0;
		else
			intCount = pItems.size();
		
		
		// added to fix bug with float printing
		DecimalFormat formatForFloats=new DecimalFormat("#.##");
		
		String bc = p.getBarcode().toString();
		String count = new Integer (intCount).toString();
		String desc = p.getDescription();
		String shelflife = new Integer (p.getShelfLife()).toString() + " months";
		//String size = p.getSize().toString() + " " + p.getUnitAsString().toLowerCase();
		
		String size = formatForFloats.format(p.getSize()) + " " + p.getUnitAsString().toLowerCase();
		String threeMonth = p.getThreeMonthSupply() + "";
		
		//fix decimal point if unit type is "count"
		if (p.getUnit() == Unit.COUNT)
		{
			size = p.getSize().intValue() + " " + p.getUnitAsString().toLowerCase();
		}

		
		ProductData pd = new ProductData();
		
		pd.setBarcode(bc);
		pd.setCount(count);
		pd.setDescription(desc);
		pd.setShelfLife(shelflife);
		pd.setSize(size);
		pd.setSupply(threeMonth);
		
		pd.setTag(p);
		
		return pd;
	}
	
	public static Unit toEnum(SizeUnits sizeUnit)
	{
		switch(sizeUnit)
		{
		case Count:
			return Unit.COUNT;
		case FluidOunces:
			return Unit.FLUID_OUNCES;
		case Gallons:
			return Unit.GALLONS;
		case Grams:
			return  Unit.GRAMS;
		case Kilograms:
			return Unit.KILOGRAMS;
		case Liters:
			return Unit.LITERS;
		case Ounces:
			return Unit.OUNCES;
		case Pints:
			return Unit.PINTS;
		case Pounds:
			return Unit.POUNDS;
		case Quarts:
			return Unit.QUARTS;
		}
		return null;
		
	}
	
	public static SizeUnits toEnum(Unit sizeUnit)
	{
		switch(sizeUnit)
		{
		case COUNT:
			return SizeUnits.Count;
		case FLUID_OUNCES:
			return SizeUnits.FluidOunces;
		case GALLONS:
			return SizeUnits.Gallons;
		case GRAMS:
			return  SizeUnits.Grams;
		case KILOGRAMS:
			return SizeUnits.Kilograms;
		case LITERS:
			return SizeUnits.Liters;
		case OUNCES:
			return SizeUnits.Ounces;
		case PINTS:
			return SizeUnits.Pints;
		case POUNDS:
			return SizeUnits.Pounds;
		case QUARTS:
			return SizeUnits.Quarts;
		}
		return null;
		
	}
}
